<?php
// 应用公共文件

use app\constant\CodeConst;
use app\admin\service\TokenService;
use app\model\AdminLogModel;


if (!function_exists('http_status')) {
    /**
     * 返回浏览器状态码
     * @param $code
     */
    function http_status($code)
    {
        static $http = [
            100 => "HTTP/1.1 100 Continue",
            101 => "HTTP/1.1 101 Switching Protocols",
            200 => "HTTP/1.1 200 OK",
            201 => "HTTP/1.1 201 Created",
            202 => "HTTP/1.1 202 Accepted",
            203 => "HTTP/1.1 203 Non-Authoritative Information",
            204 => "HTTP/1.1 204 No Content",
            205 => "HTTP/1.1 205 Reset Content",
            206 => "HTTP/1.1 206 Partial Content",
            300 => "HTTP/1.1 300 Multiple Choices",
            301 => "HTTP/1.1 301 Moved Permanently",
            302 => "HTTP/1.1 302 Found",
            303 => "HTTP/1.1 303 See Other",
            304 => "HTTP/1.1 304 Not Modified",
            305 => "HTTP/1.1 305 Use Proxy",
            307 => "HTTP/1.1 307 Temporary Redirect",
            400 => "HTTP/1.1 400 Bad Request",
            401 => "HTTP/1.1 401 Unauthorized",
            402 => "HTTP/1.1 402 Payment Required",
            403 => "HTTP/1.1 403 Forbidden",
            404 => "HTTP/1.1 404 Not Found",
            405 => "HTTP/1.1 405 Method Not Allowed",
            406 => "HTTP/1.1 406 Not Acceptable",
            407 => "HTTP/1.1 407 Proxy Authentication Required",
            408 => "HTTP/1.1 408 Request Time-out",
            409 => "HTTP/1.1 409 Conflict",
            410 => "HTTP/1.1 410 Gone",
            411 => "HTTP/1.1 411 Length Required",
            412 => "HTTP/1.1 412 Precondition Failed",
            413 => "HTTP/1.1 413 Request Entity Too Large",
            414 => "HTTP/1.1 414 Request-URI Too Large",
            415 => "HTTP/1.1 415 Unsupported Media Type",
            416 => "HTTP/1.1 416 Requested range not satisfiable",
            417 => "HTTP/1.1 417 Expectation Failed",
            500 => "HTTP/1.1 500 Internal Server Error",
            501 => "HTTP/1.1 501 Not Implemented",
            502 => "HTTP/1.1 502 Bad Gateway",
            503 => "HTTP/1.1 503 Service Unavailable",
            504 => "HTTP/1.1 504 Gateway Time-out"
        ];
        header($http[$code]);
    }
}

if (!function_exists('api')) {

    /**
     * 通用返回json
     * @param $msg
     * @param $data
     * @param $code
     * @return false|string
     */
    function api($msg, $data, $code)
    {
        $api_data = [
            'message' => $msg,
            'code' => $code,
            'time' => date('Y-m-d H:i:s',time()),
            'request_url' => request()->url(),
            'data' => $data,

        ];
        http_status(200);
        header("Content-type:application/json; charset=utf-8");
        exit(json_encode($api_data,true));
    }

}


if (!function_exists('error')) {
    /**
     * 通用失败json
     * @param $msg
     * @param int $code
     * @param array $data
     * @return false|string
     */
    function error($msg,$code =CodeConst::COMMON_ERROR,$data = [])
    {
        if (!$msg) $msg = CodeConst::COMMON_ERROR_MSG;
        return api($msg, $data, $code);
    }
}

if (!function_exists('success')) {

    /**
     * 通用成功json
     * @param $msg
     * @param array $data
     * @param int $code
     * @return false|string
     */
    function success($msg,$data = [],$code = CodeConst::SUCCESS)
    {

        if (!$msg) $msg = CodeConst::SUCCESS_MSG;;

        return api($msg, $data, $code);
    }
}



if (!function_exists('get_client_ip')) {
    /**
     * 获取ip地址
     * @return mixed|string
     */
    function get_client_ip()
    {
        $forwarded = request()->header("x-forwarded-for");
        if($forwarded){
            $ip = explode(',',$forwarded)[0];
        }else{
            $ip = request()->ip();
        }
        return $ip;

    }
}
if (!function_exists('admin_info')) {
    /**
     * 获取当前管理员信息
     * @return array
     * @throws \HyperfExt\Jwt\Exceptions\JwtException
     */
    function admin_info()
    {
        $payload = (new TokenService())->checkToken();
        return $payload;
    }
}
if (!function_exists('admin_id')) {
    /**
     * 获取当前管理员id
     * @return mixed
     * @throws \HyperfExt\Jwt\Exceptions\JwtException
     */
    function admin_id()
    {
        $payload = (new TokenService())->checkToken();
        return $payload['admin_id'];
    }
}


if (!function_exists('admin_log')) {
    /**
     * 管理员操作日志
     * @param $remark
     * @throws ErrorException
     */
    function admin_log($remark)
    {
        $admin = admin_info();

        $data = [
            'admin_id' => $admin['admin_id'],
            'username' =>$admin['username'],
            'ip' => get_client_ip(),
            'remark' => $remark,
            'action' =>request()->url()
        ];
        $result = AdminLogModel::create($data);
        if (!$result){
            throw new ErrorException('操作日志生成失败');
        }
    }
}


if (!function_exists('dd')) {
    /**
     * 调试变量并且中断输出
     * @param mixed $vars 调试变量或者信息
     */
    function dd(...$vars)
    {
        dump(...$vars);

        throw new HttpResponseException(Response::create());
    }
}

if (!function_exists('get_rand_char')) {
    /**
     * 随机生成字符串
     * @param int $length
     * @return string|null
     */
    function get_rand_char($length=16){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";//大小写字母以及数字
        $max = strlen($strPol)-1;
        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];
        }
        return $str;
    }
}



